/**********************************************************************************************
 * script.js                                                                                  *
 *                                                                                            *
 * Abstract: Script logic for the H.264Universal2010.                                    *
 *                                                                                            *
 * Version 0.1.0 (2010-04-26)                                                                 *
 * Copyright (c) 2010 Dario Caruso                                                            *
 *                                                                                            *
 **********************************************************************************************
 */

// Boolean variable
var videoIsFullScreen = false;
// Boolean variable
var muted = false;
var t = null;
var t2 = null;

// Function performed when the device is a Apple Ipad or Iphone.
function ipad_function(){
	// if the device is Apple Ipad or Iphone do
    if (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null) {
        
		// get pointers to individual DOM elements within the player
		var poster = document.getElementById("poster");
		var content = document.getElementById("right");
		var player = document.getElementById("player");
		var supported = document.getElementById("supported");
		var footer = document.getElementById("first");
		
		// remove player and poster
        content.removeChild(player);
        content.removeChild(poster);
		
		content.style.marginLeft = 550 + "px";
		content.style.height= 300 + "px";
		content.style.width=  350 + "px";
       
		// create new video tag and play the movie
        var video = document.createElement('video');
        video.id = "Ipad";
        video.width = "330";
        video.height = "250";
        video.autoplay = "autoplay";
        video.controls = "controls";
		// assigns new poster to the player
        video.poster = ("css/img/bickbuck.jpg");
        video.src = "video/video.mp4";
        content.appendChild(video);
		first.style.minHeight = 400 + "px";
		supported.style.marginTop = 100+"px";
		features.style.marginTop = 100+"px";
		supported.style.marginBottom = 150+"px";
	  }
}

/* ==================== Main initialization routine ==================== */
function start(){
    
	// after press the start button, hide the poster and play the movie
    document.getElementById("poster").style.display = "none";
    document.getElementById("player").style.display = "block";
    
    // create the player
    var player = document.getElementById('player');
    // set mouse event attribute to the player 
    player.setAttribute("onmouseover", "show()");
    player.setAttribute("onmouseout", "timeout()");
    player.setAttribute("onmousemove", "show()");

   	// save in the variable video the return function detectVideoSupport
    var video = detectVideoSupport();
    
    // both Opera and Firefox support OGG but lack MP4 support.
    // both Safari and Google Chrome support MP4 but lack OGG support.
    if (!video.mp4) {
        replaceVideoWithObject("player");
    }
    
    // if the browser doesn't support HTML5 ( for example I.E.) delete div player and create new div embedded flash player inside it
    if (!video.html5) {
		
		// get pointers to individual DOM elements within the player
		var content = document.getElementById("right");
        var player = document.getElementById("player");
        // remove player 
		content.removeChild(player);
        
		// create new div to include Flash video player
        var playerFlash = document.createElement("div");
        playerFlash.id = "playerFlash";
        content.appendChild(playerFlash);
        document.getElementById("right").style.height = "auto";
        
        // initialization Flash Player
        var flashvars = {};
        var params = {};
        var attributes = {};
        
        // parameters of the player  	
        // width and height
        var width = '470';
        var height = '400';
        
        // video url
        flashvars.hq = 'video/video.mp4';
        // autoplay
        flashvars.autoplay = "true";
        // don't edit
        params.quality = 'high';
        params.allowfullscreen = 'true';
        params.allowscriptaccess = 'sameDomain';
        params.wmode = 'transparent';
        
        // inclusion of the player
        swfobject.embedSWF('player.swf', 'playerFlash', width, height, '9.0.115', false, flashvars, params, attributes);
    }
	
    // if the browser support HTML5 and support MP4 codec do
    makePlayer("player");
}

/* ==================== No Html5 / No mp4 video support ==================== */

// detect the Browser compatibility ( HTML5, video codec )
var detectVideoSupport = function(){
    var detect = document.createElement('video') || false;
    this.html5 = detect && typeof detect.canPlayType !== "undefined";
    this.mp4 = this.html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably");
    this.ogg = this.html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably");
    return this;
};

// delete video tag and insert before it the new object that include Flash Video player
var replaceVideoWithObject = function(video_id){
    if (!video_id) {
        return false;
    }
    var video = document.getElementById(video_id);
    if (video) {
        var obj = video.getElementsByTagName("object")[0];
        if (obj) {
            video.parentNode.insertBefore(obj, video);
            var content = document.getElementById("right");
            content.removeChild(video);
        }
    }
};

/* ==================== VideoPlayer Constructor ==================== */

function makePlayer(videoID){
   	
	// get pointer to individual DOM element within the player
    var player = document.getElementById(videoID);
    
	// create controller of the player
    var controller = document.createElement('div');
    controller.id = "controls";
    player.parentNode.appendChild(controller);
    
    var playpause = document.createElement('span');
    playpause.id = "playpause";
    controller.appendChild(playpause);
    playpause.innerHTML = '<button class="play"></button>'
    
    var scrubber = document.createElement('canvas');
    scrubber.id = "scrubber";
    controller.appendChild(scrubber);
    
    var display = document.createElement('span');
    display.id = "display";
    controller.appendChild(display);
    display.innerHTML = '0:00&nbsp;/&nbsp;'
    
    var duration = document.createElement('span');
    duration.id = "duration";
    controller.appendChild(duration);
    duration.innerHTML = '--:--'
    
    var vol = document.createElement('canvas');
    vol.id = "volume";
    controller.appendChild(vol);
    
    var fscr = document.createElement('span');
    fscr.id = "fscr";
    controller.appendChild(fscr);
    fscr.innerHTML = '<button class="fs"></button>';
    
    var mute = document.createElement('span');
    mute.id = "mute";
    controller.appendChild(mute);
    mute.innerHTML = '<button class="mut"></button>';
    
	// After create the controller, call the function loadvideo()
    loadvideo();
}

function loadvideo(){
    
	// get pointers to individual DOM elements within the player
	var content = document.getElementById("main");
    var player = document.getElementById('player');
    var controller = document.getElementById('controls');
    var playbutton = document.getElementById('playpause');
    var playmute = document.getElementById('mute');
    var scrubber = document.getElementById('scrubber');
    var vol = document.getElementById('volume');
    var fullScreenControl = document.getElementById('fscr');
    
	// Create new div "fscreen" that instructs the user to how close fullscreen mode
	var fscreen = document.createElement("div");
    fscreen.id = "fscreen";
    fscreen.innerHTML = "Press Esc to exit full screen mode.";
    content.appendChild(fscreen);
    
	// show player video controls
    controller.style.display = "block";
    // set default player volume
    var volVal = 0.5;
    player.volume = volVal;
    
	// play the movie
	player.play();
    
    /* ===================== EVENT LISTENERS ====================*/
	
    /* ==================== Play / Pause  ==================== */
    playbutton.addEventListener('click', function(){
        if (player.paused) {
            player.play();
        }
        else {
            if (player.ended) {
                player.currentTime = 0;
                player.innerHTML = '<div class="pause"></div>';
                player.play();
            }
            else {
                player.pause();
            }
        }
    }, false);
    
    player.addEventListener('play', function(e){
        playbutton.innerHTML = '<button class="pause"></button>';
    }, false);
    
    player.addEventListener('pause', function(e){
        playbutton.innerHTML = '<button class="play"></button>';
    }, false);
    
    player.addEventListener('ended', function(e){
        playbutton.innerHTML = '<button class="play"></button>';
        player.load();
        fullScreenOff();
    }, false);
    
    /* ==================== Mute ==================== */
    playmute.addEventListener('click', function(){
        if (!muted) {
            playmute.innerHTML = '<button class="muted"></button>';
            player.volume = 0;
            muted = true;
            drawVolScrubber();
        }
        else {
            playmute.innerHTML = '<button class="mut"></button>';
            player.volume = 0.5;
            muted = false;
            drawVolScrubber();
        }
    }, false);
    
    /* ==================== Time Tracking ==================== */
    player.addEventListener('timeupdate', function(e){
        document.getElementById('duration').innerHTML = fixtime(player.duration);
        document.getElementById('display').innerHTML = fixtime(player.currentTime) + "&nbsp;/&nbsp;";
    }, false);
    
    // method to convert seconds into a MM:SS format.
    function fixtime(t){
        var s = t
        var h = Math.floor(s / 3600);
        s = s % 3600;
        var m = Math.floor(s / 60);
        s = Math.floor(s % 60);
        /* pad the minute and second strings to two digits */
        if (s.toString().length < 2) {
            s = "0" + s;
        }
        if (m.toString().length < 2) {
            m = "0" + m;
        }
        return m + ":" + s;
    }
    
    /* ==================== Scrubber ==================== */
    drawScrubber();
    drawVolScrubber();
    var stopper = 0;
    function drawScrubber(){
        if (scrubber.getContext) {
            scrubber.width = 400;
            scrubber.addEventListener("mousedown", function(e){
                stopper = 0;
                setScrubber(e);
                scrubber.addEventListener("mousemove", function(e){
                    setScrubber(e);
                }, false);
            }, false);
            scrubber.addEventListener("mouseup", function(e){
                stopper = 1;
            }, false);
            ctx = scrubber.getContext('2d');
            setInterval(makeScrubber, 25);
        }
    }
    
    function setScrubber(e){
        if (stopper == 0) {
            var ox = e.pageX;
            //x pos on the page itself
            var barPos = ox - findX(scrubber);
            //x position relative to canvas
            //determine percentage of x across the canvas
            var xPer = (barPos / ((scrubber.width) - 60));
            player.currentTime = player.duration * xPer;
        }
    }
    
    function makeScrubber(){
        var xpos = scrubber.width * (player.currentTime / player.duration);
        
        //drawing scrubber before current position
        for (i = 0; i <= xpos; i += 8) {
            ctx.fillStyle = "red";
            ctx.fillRect(i, 0, 8, 8);
        }
        
        //current position
        ctx.fillStyle = "#000";
        ctx.fillRect(xpos, 0, 8, 8);
        
        //after current position
        for (i = xpos + 8; i <= scrubber.width; i += 8) {
            ctx.fillStyle = "#777777";
            ctx.fillRect(i, 0, 8, 8);
        }
    }
    
    // used to determine an element’s x value in relation to the edge of the page. 
    // this is required to compare the user’s click to the location of the progress bar.
    function findX(el){
        var left = 0;
        if (el.offsetParent) {
            do {
                left += el.offsetLeft;
            }
            while (el = el.offsetParent);
            return left;
        }
    }
    
    /* ==================== Volume Scrubber ==================== */
    var vstopper = 0;
    function drawVolScrubber(){
        volVal = player.volume;
        if (vol.getContext) {
            vol.addEventListener("mousedown", function(e){
                vstopper = 0;
                setVolScrubber(e);
                vol.addEventListener("mousemove", function(e){
                    setVolScrubber(e);
                }, false);
            }, false);
            vol.addEventListener("mouseup", function(e){
                vstopper = 1;
            }, false);
            vctx = vol.getContext('2d');
            setInterval(makeVolScrubber, 25);
        }
    }
    
    function makeVolScrubber(){
        //var xpos = scrubber.width * (player.currentTime / player.duration);
        var vpos = vol.width * volVal;
        
        //drawing scrubber before current position
        for (i = 0; i <= vpos; i += 8) {
            vctx.fillStyle = "red";
            vctx.fillRect(i, 0, 8, 8);
        }
        
        //current position
        vctx.fillStyle = "black";
        vctx.fillRect(vpos, 0, 11, 8);
        
        //after current position
        for (i = vpos + 8; i <= vol.width; i += 8) {
            vctx.fillStyle = "#777777";
            vctx.fillRect(i, 0, 8, 8);
        }
    }
    
    function setVolScrubber(e){
        if (vstopper == 0) {
            var vx = e.pageX;
            //x pos on the page itself
            var vbarPos = vx - findX(vol);
            //x position relative to canvas
            //determine percentage of x across the canvas
            var vxPer = (vbarPos / vol.width)
            player.volume = 6 * vxPer;
            volVal = 6 * vxPer;
        }
        if (volVal > 0) {
            playmute.innerHTML = '<button class="mut"></button>';
        }
        if (volVal == 0) {
            playmute.innerHTML = '<button class="muted"></button>';
        }
    }
    
    /* ==================== FullScreen ==================== */
    fullScreenControl.addEventListener('click', function(){
        if (!videoIsFullScreen) {
            fullScreenOn();
        }
        else {
            fullScreenOff();
        }
    }, false);
    
    function fullScreenOn(){
        var content = document.getElementById("main");
        videoIsFullScreen = true;
        videoOrigWidth = player.offsetWidth;
        videoOrigHeight = player.offsetHeight;
        
        player.style.width = window.innerWidth + "px";
        player.style.height = window.innerHeight + "px";
        player.style.position = "fixed";
        player.style.left = -15 +"px";
        player.style.top = 20 + "px";
        
        document.getElementById("header").style.display = "none";
        document.getElementById("first").style.display = "none";
        document.getElementById("second").style.display = "none";
        document.getElementById("footer").style.display = "none";
        document.body.style.background = "black";
        
		controller.style.position = "fixed";
		controller.style.marginTop = 1000 + "px";
       	controller.style.marginLeft = -170+"px";

        fscreen.style.display = "block";
        setTimeout("hideFs()", 2000);
        
        document.onkeydown = function(e){
            if (e == null) { // ie
                keycode = event.keyCode;
            }
            else { // mozilla 
                keycode = e.which;
            }
            if (keycode == 27) {
                fullScreenOff();
            }
        };
    }
    
    function fullScreenOff(){
        videoIsFullScreen = false;
        player.style.width = videoOrigWidth + "px";
        player.style.height = videoOrigHeight + "px";
        player.style.position = "static";
        controller.style.position = "absolute";
        positionController();

        document.getElementById("header").style.display = "block";
        document.getElementById("first").style.display = "block";
        document.getElementById("second").style.display = "block";
        document.getElementById("footer").style.display = "block";
        document.getElementById("fscreen").style.display = "none";
        document.body.style.background = "url('img/section-bg.png') repeat-x 50% 0%";
    }
	// function moves the controller and makes it as wide as the video.
	function positionController(){
		var controller = document.getElementById("controls");
		controller.style.margin = -130 + "px";
		controller.style.marginLeft = 44 +"px";
	}
}

// show controls player
function show(){
    if (t != null) {
        document.getElementById("controls").style.display = "block";
        timeout();
    }
    else {
        clearTimeout(t);
        show();
    }
}

// hide controls player after 5 seconds
function timeout(){
    t = setTimeout("hide()", 5000);
}

// hide controls player
function hide(){
    document.getElementById("controls").style.display = "none";
}

// hide div fscreen 
function hideFs(){
	document.getElementById("fscreen").style.display = "none";
}
